<template>
  <div class="main-center">
    <el-card class="register-card">
      <h2>企业注册</h2>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="90px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" />
        </el-form-item>
        <el-form-item label="企业名称" prop="enterpriseName">
          <el-input v-model="form.enterpriseName" />
        </el-form-item>
        <el-form-item label="所属行业" prop="industry">
          <el-input v-model="form.industry" />
        </el-form-item>
        <el-form-item label="企业规模" prop="scale">
          <el-input v-model="form.scale" />
        </el-form-item>
        <el-form-item label="企业地址" prop="address">
          <el-input v-model="form.address" />
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="form.contact" />
        </el-form-item>
        <el-form-item v-if="errorMsg">
          <div style="color: #f56c6c; font-size: 13px;">{{ errorMsg }}</div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onRegister" :loading="loading">注册</el-button>
          <el-button @click="goLogin">返回登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from '@/utils/axios'

const router = useRouter()
const formRef = ref()
const loading = ref(false)
const errorMsg = ref('')
const form = ref({
  username: '', password: '', enterpriseName: '', industry: '', scale: '', address: '', contact: ''
})
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  enterpriseName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
  industry: [{ required: true, message: '请输入所属行业', trigger: 'blur' }],
  scale: [{ required: true, message: '请输入企业规模', trigger: 'blur' }],
  address: [{ required: true, message: '请输入企业地址', trigger: 'blur' }],
  contact: [{ required: true, message: '请输入联系方式', trigger: 'blur' }]
}
const onRegister = () => {
  formRef.value.validate(async valid => {
    if (!valid) return
    loading.value = true
    errorMsg.value = ''
    try {
      await axios.post('/register/enterprise', form.value)
      ElMessage.success('注册成功，请登录')
      router.push('/login')
    } catch (e) {
      errorMsg.value = e.message || e?.response?.data?.message || '注册失败'
    }
    loading.value = false
  })
}
const goLogin = () => router.push('/login')
</script>

<style scoped>
.register-card {
  max-width: 500px;
  margin: 60px auto;
  padding: 30px 20px;
}
</style> 